import React, { useState, useEffect } from 'react';
import { getPermissionsListFromApi, permissionsStore, getButtonPermissionsListFromApi } from '@/store/permissions/permissionsStore'
import { DownOutlined } from '@ant-design/icons';
import { Tree, Checkbox } from 'antd';

const Permissions = () => {
    // 使用 useState 来管理状态
    const [permissions, setPermissions] = useState(permissionsStore.getState().permissionsList);
    const [buttonPermissions, setButtonPermissions] = useState(permissionsStore.getState().buttonPermissionsList);

    // 点击树形结构
    const onSelect = (selectedKeys, info) => {
        console.log('selected', selectedKeys, info);
    };

    // 点击复选框
    const onChange = (checkedValues, nodeId) => {
        console.log('checked = ', checkedValues, 'nodeId = ', nodeId);
        // 将选中的按钮ID转换为完整的按钮对象
        const selectedButtons = buttonPermissions.filter(btn => checkedValues.includes(btn._id));
        
        // 更新权限列表中的按钮（支持三级结构）
        const newPermissions = permissions.map(item => {
            if (item._id === nodeId) {
                return { ...item, buttons: selectedButtons };
            }
            if (item.children) {
                return {
                    ...item,
                    children: item.children.map(child => {
                        if (child._id === nodeId) {
                            return { ...child, buttons: selectedButtons };
                        }
                        if (child.children) {
                            return {
                                ...child,
                                children: child.children.map(grandchild =>
                                    grandchild._id === nodeId
                                        ? { ...grandchild, buttons: selectedButtons }
                                        : grandchild
                                )
                            };
                        }
                        return child;
                    })
                };
            }
            return item;
        });
        setPermissions(newPermissions);
        // TODO: 调用API保存更新后的权限
    };

    // 自定义渲染树节点
    const titleRender = (nodeData) => {
        // 查找当前节点（支持三级结构）
        const currentNode = permissions.find(item => item._id === nodeData.key) ||
            permissions.flatMap(item => item.children || []).find(child => child._id === nodeData.key) ||
            permissions.flatMap(item => 
                (item.children || []).flatMap(child => 
                    child.children || []
                )
            ).find(grandchild => grandchild._id === nodeData.key);

        // 获取当前节点已选中的按钮ID列表
        const checkedButtonIds = currentNode?.buttons?.map(btn => btn._id) || [];
        
        return (
            <div style={{ 
                display: 'flex', 
                alignItems: 'center',
                justifyContent: 'space-between', // 在两端对齐
                width: '100%',  // 占满整行
                padding: '4px 0',  // 增加一些上下间距
            }}>
                <span style={{ 
                    minWidth: '120px'  // 确保标题有最小宽度
                }}>{nodeData.title}</span>
                <Checkbox.Group
                    options={buttonData}
                    value={checkedButtonIds}
                    onChange={(checkedValues) => onChange(checkedValues, nodeData.key)}
                    style={{
                        display: 'flex',
                        gap: '16px',  // 复选框之间的间距
                        flexWrap: 'nowrap',  // 防止换行
                    }}
                />
            </div>
        );
    };

    // 转换成树形结构
    const treeData = permissions.map((item) => ({
        title: item.name,
        key: item._id,
        children: item.children?.map((child) => ({
            title: child.name,
            key: child._id,
            children: child.children?.map((grandchild) => ({
                title: grandchild.name,
                key: grandchild._id
            }))
        }))

    }));
    // console.log(treeData, 'treeData');
    
    // 转换成按钮权限checkbox结构
    const buttonData = buttonPermissions.map((item) => ({
        label: item.name,
        value: item._id
    }));

    // 获取列表并设置监听
    useEffect(() => {
        const fetchData = async () => {
            await getPermissionsListFromApi();
            await getButtonPermissionsListFromApi();
            // console.log('permissions', permissions);
            
            // 从 store 获取最新数据
            const storeState = permissionsStore.getState();
            setPermissions(storeState.permissionsList);
            setButtonPermissions(storeState.buttonPermissionsList);
        };

        fetchData();

        // 订阅 store 变化
        const unsubscribe = permissionsStore.subscribe(() => {
            const storeState = permissionsStore.getState();
            setPermissions(storeState.permissionsList);
            setButtonPermissions(storeState.buttonPermissionsList);
        });

        return () => unsubscribe();
    }, []);

    return (
        <div style={{
            padding: '24px',  // 增加整体内边距
            background: '#fff'  // 白色背景
        }}>
            <Tree
                showLine
                switcherIcon={<DownOutlined />}
                defaultExpandAll={true}
                onSelect={onSelect}
                treeData={treeData}
                titleRender={titleRender}
                style={{
                    width: '100%',  // 树形控件占满容器宽度
                    fontSize: '14px'  // 调整字体大小
                }}
            />
        </div>
    );
};

export default Permissions;